<template>
  <div class="bs-wrapper" ref="bsWrapper">
    <slot></slot>
  </div>
</template>

<script type="text/ecmascript-6">
import BScroll from 'better-scroll'

export default {
  name: 'scroll',
  props: {
    delayTime: {
      type: Number,
      default: 30
    },
    data: {
      type: Array,
      default: null
    },
    probeType: {
      type: Number,
      default: 1
    },
    click: {
      type: Boolean,
      default: true
    },
    needEmitScroll: {
      type: Boolean,
      default: false
    },
    pullup: {
      type: Boolean,
      default: false
    },
    beforeScroll: { // 是否触发，开始滚动前事件
      type: Boolean,
      default: false
    }
  },
  methods: {
    refresh() {
      if (this.scroll) {
        this.$nextTick(() => {
          this.scroll.refresh()
        })
      }
    },
    scrollToElement() {
      this.scroll.scrollToElement.apply(this.scroll, arguments)
    },
    _initScroll() {
      if (!this.$refs.bsWrapper) {
        return
      }
      this.scroll = new BScroll(this.$refs.bsWrapper, {
        probeType: this.probeType,
        click: this.click
      })
      if (this.pullup) {
        this.scroll.on('scrollEnd', (pos) => {
          if (pos.y <= this.scroll.maxScrollY) {
            this.$emit('pullingUp', pos.y, this.scroll.maxScrollY)
          }
        })
      }
      if (this.beforeScroll) {
        this.scroll.on('beforeScrollStart', () => {
          this.$emit('beforeScroll')
        })
      }
    },
    _defineEmitScroll() {
      if (this.needEmitScroll && this.scroll) {
        this.scroll.on('scroll', (pos) => {
          this.$emit('scroll', pos)
        })
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this._initScroll()
        this._defineEmitScroll()
      }, this.delayTime)
    })
  },
  watch: {
    data() {
      setTimeout(() => {
        this.refresh()
      }, this.delayTime)
    }
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
.bs-wrapper
  overflow: hidden
</style>
